package cn.icybear.orzjisp;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.util.Scanner;

import cn.icybear.orzjisp.compiler.CodeCompiler;
import cn.icybear.orzjisp.compiler.CompileException;
import cn.icybear.orzjisp.orzvm.OrzLoader;
import cn.icybear.orzjisp.orzvm.OrzVM;
import cn.icybear.orzjisp.parser.CodeParser;
import cn.icybear.orzjisp.parser.ParseException;
import cn.icybear.orzjisp.parser.TokenMgrError;

public class OrzConsole {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String l = "";
		StringBuilder buf = new StringBuilder();
		CodeParser parser = null;
		CodeCompiler cc = new CodeCompiler();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		OrzLoader loader = null;
		OrzVM vm = new OrzVM();
		while (!l.equals("quit")) {
			System.out.print(">");
			System.out.flush();
			l = sc.nextLine();
			if (l.endsWith(";")) {
				buf.append(l.substring(0, l.length() - 1));
				buf.append('\n');
				try {
					if (parser == null)
						parser = new CodeParser(
								new StringReader(buf.toString()));
					else
						parser.ReInit(new StringReader(buf.toString()));
					cc.compile(os, parser.getHead());
					loader = new OrzLoader();
					loader.load(os.toByteArray());
					vm.execute(loader);
					os.reset();
					buf = new StringBuilder();
					System.gc();
				} catch (CompileException e) {
					System.out.println("CompileError:" + e);
				} catch (ParseException e) {
					System.out.println("ParseError:" + e);
				} catch (TokenMgrError e) {
					System.out.println("Error:" + e);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			} else {
				buf.append(l);
				buf.append('\n');
			}
		}
	}

}
